<template>
  <el-dialog
    v-model="visible"
    :title="!dataForm.employeeId ? $t('product.addNew') : $t('temp.modify')"
    :close-on-click-modal="false"
    width="568px"
    @close="handleDialogClose"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      :label-width="$t('language') == '简体中文'?'80px':'100px'"
      @submit.prevent
      @keyup.enter="onSubmit()"
    >
      <el-form-item
        :label="$t('sys.nickName')"
        prop="nickName"
      >
        <el-input
          v-model="dataForm.nickName"
          maxlength="20"
          :placeholder="$t('sys.nickName')"
        />
      </el-form-item>
      <el-form-item
        :label="$t('sys.userName')"
        prop="userName"
      >
        <el-input
          v-model="dataForm.userName"
          :placeholder="$t('sys.userName')"
          :disabled="dataForm.type === 0"
        />
      </el-form-item>
      <el-form-item
        :label="$t('shop.phoneNumber')"
        prop="mobile"
      >
        <el-input
          v-model="dataForm.mobile"
          maxlength="11"
          :placeholder="$t('shop.phoneNumber')"
        />
      </el-form-item>
      <el-form-item
        :label="$t('sys.password')"
        prop="password"
        :class="{ 'is-required': !dataForm.employeeId }"
      >
        <el-input
          v-model="dataForm.password"
          v-input-rule
          type="password"
          maxlength="20"
          :placeholder="$t('sys.password')"
        />
      </el-form-item>
      <el-form-item
        :label="$t('sys.confirmPassword')"
        prop="comfirmPassword"
        :class="{ 'is-required': !dataForm.employeeId }"
      >
        <el-input
          v-model="dataForm.comfirmPassword"
          v-input-rule
          type="password"
          maxlength="20"
          :placeholder="$t('sys.confirmPassword')"
        />
      </el-form-item>
      <el-form-item
        :label="$t('sys.email')"
        prop="email"
      >
        <el-input
          v-model="dataForm.email"
          :placeholder="$t('sys.email')"
        />
      </el-form-item>
      <el-form-item
        v-if="roleList.length && dataForm.type !== 0"
        :label="$t('sys.roles')"
        prop="roleIdList"
      >
        <el-checkbox-group v-model="dataForm.roleIdList">
          <el-checkbox
            v-for="role in roleList"
            :key="role.roleId"
            :label="role.roleId"
          >
            {{ role.roleName }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item
        v-if="dataForm.type !== 0"
        :label="$t('product.status')"
        prop="status"
      >
        <el-radio-group v-model="dataForm.status">
          <el-radio :label="0">
            {{ $t('publics.disable') }}
          </el-radio>
          <el-radio :label="1">
            {{ $t('publics.normal') }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <div
          class="default-btn"
          @click="visible = false"
        >
          {{ $t('crud.filter.cancelBtn') }}
        </div>
        <div
          class="default-btn primary-btn"
          @click="onSubmit()"
        >
          {{ $t('crud.filter.submitBtn') }}
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { isEmail, isMobile, isUserName, validPassword } from '@/utils/validate'
import { encrypt } from '@/utils/crypto'
import { ElMessage } from 'element-plus'

const emit = defineEmits(['refreshDataList'])

const dataForm = reactive({
  employeeId: 0,
  userName: '',
  nickName: '',
  password: '',
  comfirmPassword: '',
  email: '',
  mobile: '',
  roleIdList: [],
  status: 1,
  type: '',
  userId: '',
  shopId: 0,
  createEmployeeId: 0
})

const validateUsername = (rule, value, callback) => {
  if (!isUserName(value)) {
    callback(new Error($t('homes.InputCorrectUsername')))
  } else {
    callback()
  }
}
const validatePassword = (rule, value, callback) => {
  if (!dataForm.employeeId && !/\S/.test(value)) {
    callback(new Error($t('sys.passwordNoNull')))
  } else if (!(dataForm.employeeId && !value) && !validPassword(value)) {
    callback(new Error($t('passwordVerification')))
  } else {
    callback()
  }
}
const validateComfirmPassword = (rule, value, callback) => {
  if (!dataForm.employeeId && !/\S/.test(value)) {
    callback(new Error($t('sys.confirmPassNoNull')))
  } else if (dataForm.password !== value) {
    callback(new Error($t('sys.passworldContrast')))
  } else {
    callback()
  }
}
const validateEmail = (rule, value, callback) => {
  if (!isEmail(value)) {
    callback(new Error($t('sys.emailaError')))
  } else {
    callback()
  }
}
const validateMobile = (rule, value, callback) => {
  if (dataForm.mobile) {
    const mobile = /^(?:(?:\+|00)86)?1\d{2}([\d*]{4})\d{4}$/
    if (mobile.test(value)) {
      callback()
    } else {
      callback(new Error($t('language') === '简体中文' ? '请输入正确的手机号' : 'Please enter valid mobile'))
    }
  } else if (!isMobile(value)) {
    callback(new Error($t('sys.mobilePhoneError')))
  } else {
    callback()
  }
}
const dataRule = {
  userName: [
    { required: true, validator: validateUsername, trigger: 'blur' }
  ],
  nickName: [
    { required: true, message: $t('sys.nickNameNoNull'), trigger: 'blur' },
    { min: 2, max: 20, message: $t('sys.nickNameBetween'), trigger: 'blur' }
  ],
  password: [
    { validator: validatePassword, trigger: 'blur' }
  ],
  comfirmPassword: [
    { validator: validateComfirmPassword, trigger: 'blur' }
  ],
  email: [
    { required: true, message: $t('sys.emailaNoNull'), trigger: 'blur' },
    { validator: validateEmail, trigger: 'blur' }
  ],
  mobile: [
    { required: true, message: $t('sys.mobilePhoneNoNull'), trigger: 'blur' },
    { validator: validateMobile, trigger: 'blur' }
  ]
}

let isSubmit = false
const roleList = ref([])
const visible = ref(false)
const dataFormRef = ref(null)
const init = (id) => {
  dataForm.employeeId = id || 0
  isSubmit = false
  http({
    url: http.adornUrl('/sys/shopRole/list'),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    roleList.value = data
  }).then(() => {
    visible.value = true
    nextTick(() => {
      dataFormRef.value?.resetFields()
    })
  }).then(() => {
    if (dataForm.employeeId) {
      http({
        url: http.adornUrl(`/sys/shopEmployee/info/${dataForm.employeeId}`),
        method: 'get',
        params: http.adornParams()
      }).then(({ data }) => {
        dataForm.userName = data.username
        dataForm.nickName = data.nickname
        dataForm.email = data.email
        dataForm.mobile = data.mobile
        dataForm.roleIdList = data.roleIdList
        dataForm.status = data.status
        dataForm.type = data.type
      })
    }
  })
}

// 表单提交
const onSubmit = () => {
  dataFormRef.value?.validate((valid) => {
    if (valid) {
      if (isSubmit) {
        return false
      }
      isSubmit = true
      http({
        url: http.adornUrl('/sys/shopEmployee'),
        method: dataForm.employeeId ? 'put' : 'post',
        data: http.adornData({
          employeeId: dataForm.employeeId || undefined,
          username: dataForm.userName,
          nickname: dataForm.nickName,
          password: encrypt(dataForm.password),
          email: dataForm.email,
          mobile: dataForm.mobile,
          status: dataForm.status,
          roleIdList: dataForm.roleIdList
        })
      }).then(() => {
        ElMessage({
          message: $t('publics.operation'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            visible.value = false
            emit('refreshDataList')
          }
        })
      }).catch(() => {
        isSubmit = false
      })
    }
  })
}

const handleDialogClose = () => {
  roleList.value = []
  dataForm.type = ''
}

defineExpose({
  init
})

</script>
